package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Company;
import com.okq.entity.Group;
import com.okq.entity.Role;
import com.okq.entity.User;
import com.okq.service.ICompanyService;
import com.okq.service.IGroupService;
import com.okq.service.ILogService;
import com.okq.service.IRoleService;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 公司Action
 * 作者 : zdl
 * 日期 : 2017/6/28 10:58
 */
public class CompanyAction extends BaseActionSupport {

    private static final long serialVersionUID = 5620504011647690502L;

    /**
     * 公司接口
     */
    @Autowired
    private ICompanyService companyServiceImpl;
    /**
     * 部门接口
     */
    @Autowired
    private IGroupService groupServiceImpl;
    /**
     * 角色接口
     */
    @Autowired
    private IRoleService roleServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(CompanyAction.class);

    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;
    /**
     * 公司名称
     */
    private String companyName;
    /**
     * 公司ID
     */
    private String id;
    /**
     * 公司实体
     */
    private Company company;
    /**
     * 操作类型
     */
    private String type;

    /**
     * 获取公司列表
     *
     * @return Map的json
     */
    public String getCompanyList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Company> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                Company company = new Company();
                company.setName(companyName);
                pageInfo = companyServiceImpl.pageByCompany(pageInfo, company);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Company> comList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> comMapList = new ArrayList<>();
                if (comList != null && !comList.isEmpty() && comList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Company com : comList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", com.getId());
                        map.put("companyName", StringUtils.defaultString(com.getName(), ""));
                        map.put("address", StringUtils.defaultString(com.getAddress(), ""));
                        map.put("contacts", StringUtils.defaultString(com.getContacts(), ""));
                        map.put("cellphone", StringUtils.defaultString(com.getCellphone(), ""));
                        map.put("telephone", StringUtils.defaultString(com.getTelephone(), ""));
                        map.put("fax", StringUtils.defaultString(com.getFax(), ""));
                        map.put("email", StringUtils.defaultString(com.getEmail(), ""));
                        map.put("createTime", TimeTool.timestampToString(com.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        comMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", comMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 是否成功标识符
     */
    public String deleteCompany() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                List<Group> gList = groupServiceImpl.listGroupByComId(id);
                if (gList != null && !gList.isEmpty() && gList.size() > 0) {
                    out.print(1);
                    return null;
                } else {
                    Company com = companyServiceImpl.getCompanyById(id);
                    if (com != null) {
                        // 修改删除状态
                        com.setIsDelete(1);
                        com.setUpdateUserId(loginUser.getId());
                        com.setUpdateUserName(loginUser.getUserName());
                        companyServiceImpl.updateCompany(com);
                        out.print(0);
                        //添加系统日志
                        String userName = loginUser.getUserName();
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 删除公司：" + com.getName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "公司管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到详情页面/修改页面
     *
     * @return update/detail
     */
    @SuppressWarnings("all")
    public String toUpdateOrDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                company = companyServiceImpl.getCompanyById(id);
                if (company != null) {
                    if (type.equals("update")) {
                        return "update";
                    } else if (type.equals("detail")) {
                        return "detail";
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 是否成功标识符
     */
    public String saveCompany() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && company != null) {
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    Company com = companyServiceImpl.getCompanyByName(company.getName());
                    if (com != null) {
                        out.print("exist");
                        return null;
                    } else {
                        company.setId(BaseTool.getPK());
                        company.setComCode(getComCode());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            company.setCreateUserId(loginUser.getId());
                            company.setCreateUserName(userName);
                        }
                        companyServiceImpl.saveCompany(company);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 添加公司：" + company.getName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "公司管理", 2, content, logServiceImpl);
                    }
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    String newName = company.getName();
                    Company com = companyServiceImpl.getCompanyById(company.getId());
                    if (com != null) {
                        String oldName = com.getName();
                        if (StringUtils.isNotBlank(newName) && StringUtils.isNotBlank(oldName) && !newName.equals(oldName)) {
                            Company c = companyServiceImpl.getCompanyByName(newName);
                            if (c != null) {
                                out.print("exist");
                                return null;
                            }
                        }
                        com.setName(newName);
                        com.setAddress(company.getAddress());
                        com.setContacts(company.getContacts());
                        com.setCellphone(company.getCellphone());
                        com.setTelephone(company.getTelephone());
                        com.setFax(company.getFax());
                        com.setEmail(company.getEmail());
                        com.setRemark(company.getRemark());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            com.setUpdateUserId(loginUser.getId());
                            com.setUpdateUserName(userName);
                        }
                        companyServiceImpl.updateCompany(com);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改公司：" + newName + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "公司管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 根据登录用户角色获取对应的公司信息
     *
     * @return 公司集合Json
     */
    public String getAllCompany() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                List<Company> cList = new ArrayList<>();
                String roleId = loginUser.getRoleId();
                if (StringUtils.isNotBlank(roleId)) {
                    Role role = roleServiceImpl.getRoleById(roleId);
                    if (role != null) {
                        Integer roleType = role.getRoleType();
                        if (roleType == 0) {// 超级管理员
                            cList = companyServiceImpl.listAllCompany();
                        } else {
                            String comCode = loginUser.getComCode();
                            if (StringUtils.isNotBlank(comCode)) {
                                Company company = companyServiceImpl.getCompanyByComCode(comCode);
                                if (company != null) {
                                    cList.add(company);
                                }
                            }
                        }
                    }
                }
                String data = BaseTool.toJson(cList);
                out.print(data);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取公司代码
     *
     * @return 公司代码
     */
    private String getComCode() {
        String comCode = "";
        try {
            Company com = companyServiceImpl.getLastCompany();
            if (com != null) {
                String companyCode = com.getComCode();
                if (StringUtils.isNotBlank(companyCode)) {
                    Integer codeNum = Integer.valueOf(companyCode.substring(5, companyCode.length()));
                    comCode = companyCode.substring(0, 5) + BaseTool.zeroFormat("000", codeNum + 1);
                } else {
                    comCode = BaseTool.getNum();
                }
            } else {
                comCode = BaseTool.getNum();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return comCode;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}
